package com.vigor.bear.web.controller;

import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vigor.bear.shiro.HashUtils;
import com.vigor.bear.web.bean.JsonModel;
import com.vigor.bear.web.bean.QueryModel;
import com.vigor.bear.web.bean.Role;
import com.vigor.bear.web.bean.User;
import com.vigor.bear.web.exception.OperationNotAllowedException;
import com.vigor.bear.web.service.RoleService;
import com.vigor.bear.web.service.UserService;
import com.vigor.bear.web.utils.DatatableUtils;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService usv;

	@Autowired
	private RoleService rsv;

	@InitBinder("user")
	public void initUserBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("user.");
	}

	@RequestMapping(method = RequestMethod.GET)
	public String view(Model model) {
		return "system/user/list";
	}

	@RequestMapping(value = "/toList", method = RequestMethod.GET)
	public String toList() {
		return "system/user/list";
	}

	@RequiresPermissions("user:view")
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> list(@RequestBody String aoData) {
		QueryModel queryModel = DatatableUtils.getQueryModel(aoData);
		return DatatableUtils.getQueryResult(queryModel, usv.all(queryModel));
	}

	@RequestMapping(value = "/toCreate", method = RequestMethod.GET)
	public String toCreate(Model model) {
		List<Role> roles = rsv.all();
		model.addAttribute("roles", roles);
		return "system/user/add";
	}
	
	@RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
	@ResponseBody
	public JsonModel checkUsername(@RequestParam("username") String username,
			JsonModel json) {
		int ret = 0;
		User user = usv.find(username);
		if (user != null) {
			ret = 1;
		}
		handleJsonModel(json, ret, "查询用户");
		return json;
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(User user, Model model) {
		user.setPassword(HashUtils.md5(user.getPassword()));
		int ret = usv.create(user);
		if (ret > 0) {
			model.addAttribute("result",
					"{\"success\":\"true\",\"message\":\"创建成功!\",\"url\":\"/user\"}");
		} else {
			model.addAttribute("result",
					"{\"success\":\"false\",\"message\":\"创建失败!\",\"url\":\"/user/toCreate\"}");
		}
		return "common/__result";
	}

	@RequestMapping(value = "/toUpdate/{uid}", method = RequestMethod.GET)
	public String toUpdate(@PathVariable("uid") int uid, Model model) {
		List<Role> roles = rsv.all();
		model.addAttribute("roles", roles);
		User user = usv.get(uid);
		model.addAttribute("user", user);
		return "system/user/edit";
	}

	@RequiresPermissions("user:eidt")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(User user, Model model) {
		int ret = usv.update(user);
		if (ret > 0) {
			model.addAttribute("result",
					"{\"success\":\"true\",\"message\":\"更新成功!\",\"url\":\"/user\"}");
		} else {
			model.addAttribute("result",
					"{\"success\":\"false\",\"message\":\"更新失败!\",\"url\":\"/user/toUpdate\"}");
		}
		return "common/__result";
	}

	@RequiresPermissions("user:delete")
	@RequestMapping(value = "/{uid}/delete", method = RequestMethod.GET)
	@ResponseBody
	public JsonModel delete(@PathVariable("uid") int uid, JsonModel json) {
		if (uid == 1)
			throw new OperationNotAllowedException("不能删除默认管理员账户");
		int ret = usv.delete(uid);
		handleJsonModel(json, ret, "删除");
		return json;
	}

	@RequiresPermissions("user:deleteSelect")
	@RequestMapping(value = "/deleteSelect", method = RequestMethod.GET)
	@ResponseBody
	public JsonModel deleteSelect(@RequestParam("uids") String uids,
			JsonModel json) {
		if (containsSuperUser(uids)) {
			throw new OperationNotAllowedException("不能删除默认管理员账户");
		}
		int ret = usv.deleteSelect(uids.split(","));
		handleJsonModel(json, ret, "删除所选");
		return json;
	}

	@RequiresAuthentication
	@RequestMapping(value = "/password", method = RequestMethod.GET)
	public String password(Model model) {
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		model.addAttribute("user", usv.find(username));
		return "system/user/password";
	}

	@RequiresAuthentication
	@RequestMapping(value = "/{uid}/password", method = RequestMethod.POST)
	@ResponseBody
	public JsonModel password(@PathVariable("uid") int uid, String newPassword,
			JsonModel json) {
		User user = new User();
		user.setUid(uid);
		user.setPassword(HashUtils.md5(newPassword));
		int ret = usv.update(user);
		handleJsonModel(json, ret, "修改");
		return json;
	}

	private void handleJsonModel(JsonModel json, int ret, String op) {
		json.setSuccess(ret > 0);
		json.setMessage(op + (ret > 0 ? "成功" : "失败"));
	}

	private boolean containsSuperUser(String uids) {
		boolean temp = false;

		String[] uidArr = uids.split(",");
		for (String uid : uidArr) {
			if ("1".equals(uid)) {
				temp = true;
			}
		}

		return temp;
	}

}
